 # encoding: utf-8

require 'digest/sha1'

class User < ActiveRecord::Base


	has_one :cart

  EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i

  validates_length_of :password, :within => 5..20, :on => :create
  validates :name,:presence => true, :length => { :within => 3..30 }, :uniqueness => true
  validates_confirmation_of :password

  validates :phone, :length => { :maximum => 15}
  validates :address,:presence => true, :length => { :maximum => 50}

  validates :email, :presence => true, :length => { :maximum => 30 }, 
    :format => EMAIL_REGEX, :confirmation => true
	  
  attr_accessor :password
	attr_protected :id, :salt

  before_save :password
 

	def self.authenticate(name="", pass="")
	    #u=User.find(:first, :condition => ["name = ?", name])
	    #return nil if u.nil?
	    #return u if User.encrypt(pass, u.salt)==u.hashed_password
	    #nil
      user = User.find(:first, :conditions => ["name = ?", name])
      if user && User.encrypt(pass, user.salt)==user.hashed_password
        return user
      else 
        return nil
      end
  end 

  def password=(pass)
  	@password=pass
  	self.salt = User.random_string(10) if !self.salt?
  	self.hashed_password = User.encrypt(@password, self.salt)
  end

  def send_new_password
    new_pass = User.random_string(10)
    self.password = self.password_confirmation = new_pass
    self.save
    Notifications.forgot_password(self.email, self.name, new_pass).deliver
    #Notifications.mail_to(self.email).deliver
  end	

  protected

  def self.encrypt(pass="", salt="")
  	Digest::SHA1.hexdigest(pass+salt)
  end

	def self.random_string(len)
    	#generat a random password consisting of strings and digits
  	chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  	newpass = ""
  	1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
  	return newpass
  end

end
